"""
=========================================================================
Music Library Management System

Complete all functions below. Do not modify function names or parameters.
Test your code using the test cases at the bottom of the file.
=========================================================================
"""

def create_artist_db(artist_list):
    """
    Create a dictionary of artists from a list of tuples.

    Args:
        artist_list: List of tuples [(artist_name, genre, country), ...]

    Returns:
        Dictionary with artist names as keys and dictionaries of details as values
        Format: {artist_name: {"genre": genre, "country": country}, ...}

    Example:
        >>> artists = [("Taylor Swift", "Pop", "USA"), ("Ed Sheeran", "Pop", "UK")]
        >>> create_artist_db(artists)
        {'Taylor Swift': {'genre': 'Pop', 'country': 'USA'},
         'Ed Sheeran': {'genre': 'Pop', 'country': 'UK'}}
    """
    # YOUR CODE HERE
    artist_dic = {}
    for i in artist_list:

        name, genre, country =i
        sub_d ={}
        sub_d["genre"] =i[1]
        sub_d["country"]= i[2]
        artist_dic[name]=sub_d

    return artist_dic  # Placeholder: return empty dictionary



def build_playlist(song_list, playlist_name):
    """
    Build a playlist dictionary from a list of songs.

    Args:
        song_list: List of tuples [(song_name, artist, duration_seconds), ...]
        playlist_name: String name for the playlist

    Returns:
        Dictionary with keys: 'name', 'songs', 'total_duration', 'song_count'

    Example:
        >>> songs = [("Shake It Off", "Taylor Swift", 219), ("Perfect", "Ed Sheeran", 263)]
        >>> build_playlist(songs, "Favorites")
        {'name': 'Favorites', 'songs': [...], 'total_duration': 482, 'song_count': 2}
    """
    # YOUR CODE HERE
    song_counter = 0
    songlist=[]
    totaldur = 0
    for i in song_list:

        song_counter+=1
        songname,artst,dur = i
        songlist.append(songname)
        
        totaldur +=dur



    return {
        'name': playlist_name,
        'songs': songlist,
        'total_duration':totaldur ,
        'song_count': song_counter
    }  # Placeholder: return empty playlist structure


def organize_by_artist(song_list):
    """
    Organize songs by artist into a dictionary.

    Args:
        song_list: List of tuples [(song_name, artist, duration), ...]

    Returns:
        Dictionary {artist_name: [(song_name, duration), ...], ...}

    Example:
        >>> songs = [("Song1", "Artist1", 180), ("Song2", "Artist1", 200),
        ...          ("Song3", "Artist2", 150)]
        >>> organize_by_artist(songs)
        {'Artist1': [('Song1', 180), ('Song2', 200)],
         'Artist2': [('Song3', 150)]}
    """
    # YOUR CODE HERE


    d={}
    for i in song_list:

        title,artist,dur = i
        k = (title,dur)
        l = [k]
        #d[artist]=[title,dur]
        if artist not in d:
            #l.append(k)
            d[artist]=l

        else:
            l.append(k)
           # d[artist]=l

    return d  # Placeholder: return empty dictionary


def find_songs_by_artist(music_library, artist_name):
    """
    Find all songs by a specific artist.

    Args:
        music_library: Dictionary from organize_by_artist() function
        artist_name: String name of artist to search for

    Returns:
        List of song names (strings only), or empty list if artist not found

    Example:
        >>> library = {'Artist1': [('Song1', 180), ('Song2', 200)]}
        >>> find_songs_by_artist(library, 'Artist1')
        ['Song1', 'Song2']
        >>> find_songs_by_artist(library, 'Artist3')
        []
    """
    # YOUR CODE HERE
    return []  # Placeholder: return empty list


def find_long_songs(song_list, min_duration):
    """
    Find all songs with duration greater than or equal to min_duration.

    Args:
        song_list: List of tuples [(song_name, artist, duration), ...]
        min_duration: Integer minimum duration in seconds

    Returns:
        List of tuples for songs with duration >= min_duration

    Example:
        >>> songs = [("Song1", "Artist1", 180), ("Song2", "Artist2", 250)]
        >>> find_long_songs(songs, 200)
        [('Song2', 'Artist2', 250)]
    """
    # YOUR CODE HERE
    longs=[]
    for i in song_list:
        title,artist,dur = i
        if dur >= min_duration:
            longs.append(i)

    return longs  # Placeholder: return empty list


def get_longest_song(song_list):
    """
    Find the longest song in the list.

    Args:
        song_list: List of tuples [(song_name, artist, duration), ...]

    Returns:
        Tuple of the longest song (song_name, artist, duration)
        If list is empty, return None

    Example:
        >>> songs = [("Song1", "Artist1", 180), ("Song2", "Artist2", 250)]
        >>> get_longest_song(songs)
        ('Song2', 'Artist2', 250)
    """
    # YOUR CODE HERE
    """
    if not song_list:
        result = None
    else:
        max_item = song_list[0]
        for song in song_list:
            if song > max_item:
                max_item = song
                """
    if not song_list:
        return None
    else:
        max_tuple = song_list[0]
        for i in song_list:
            if i[2] > max_tuple[2]:
                max_tuple= i




    return max_tuple  # Placeholder: return None


def get_artist_with_most_songs(music_library):
    """
    Find the artist with the most songs in the library.

    Args:
        music_library: Dictionary from organize_by_artist() function
                      {artist_name: [(song_name, duration), ...], ...}

    Returns:
        String name of artist with most songs
        If library is empty, return None
        If there's a tie, return any one of the tied artists

    Example:
        >>> library = {'Artist1': [('Song1', 180), ('Song2', 200)],
        ...            'Artist2': [('Song3', 150)]}
        >>> get_artist_with_most_songs(library)
        'Artist1'
    """
    # YOUR CODE HERE
    return None  # Placeholder: return None


# ============================================================================
# TEST CASES - Run these to test your implementations
# ============================================================================

if __name__ == "__main__":
    print("=" * 60)
    print("Testing Music Library Management System")
    print("=" * 60)

    # Test data - expanded dataset
    test_artists = [
        ("Taylor Swift", "Pop", "USA"),
        ("Ed Sheeran", "Pop", "UK"),
        ("Metallica", "Metal", "USA"),
        ("Adele", "Pop", "UK"),
        ("Gracie Abrams", "Indie Pop", "USA"),
        ("The Weeknd", "R&B", "Canada"),
        ("Billie Eilish", "Alternative", "USA")
    ]

    test_songs = [
        # Taylor Swift - 4 songs
        ("Shake It Off", "Taylor Swift", 219),
        ("Blank Space", "Taylor Swift", 231),
        ("Anti-Hero", "Taylor Swift", 200),
        ("Cruel Summer", "Taylor Swift", 178),

        # Ed Sheeran - 3 songs
        ("Shape of You", "Ed Sheeran", 233),
        ("Perfect", "Ed Sheeran", 263),
        ("Thinking Out Loud", "Ed Sheeran", 281),

        # Metallica - 3 songs
        ("Enter Sandman", "Metallica", 331),
        ("Nothing Else Matters", "Metallica", 388),
        ("Master of Puppets", "Metallica", 515),

        # Adele - 2 songs
        ("Hello", "Adele", 295),
        ("Someone Like You", "Adele", 285),

        # Gracie Abrams - 4 songs
        ("I miss you, I'm sorry", "Gracie Abrams", 169),
        ("21", "Gracie Abrams", 162),
        ("That's So True", "Gracie Abrams", 156),
        ("Risk", "Gracie Abrams", 193),

        # The Weeknd - 3 songs
        ("Blinding Lights", "The Weeknd", 200),
        ("Starboy", "The Weeknd", 230),
        ("Save Your Tears", "The Weeknd", 215),

        # Billie Eilish - 2 songs
        ("bad guy", "Billie Eilish", 194),
        ("Happier Than Ever", "Billie Eilish", 298)
    ]

    # Test Task 1
    print("\n--- Task 1: Create Artist Database ---")
    try:
        artist_db = create_artist_db(test_artists)
        if artist_db:
            print(f"✓ Created database with {len(artist_db)} artists")
            taylor_info = artist_db.get('Taylor Swift', 'Not found')
            print(f"  Taylor Swift info: {taylor_info}")
            gracie_info = artist_db.get('Gracie Abrams', 'Not found')
            print(f"  Gracie Abrams info: {gracie_info}")
        else:
            print("⚠ Function returns empty dictionary - implement Task 1")
    except Exception as e:
        print(f"✗ Error in Task 1: {e}")

    # Test Task 2
    print("\n--- Task 2: Build Playlist ---")
    try:
        my_playlist = build_playlist(test_songs[:5], "Top 5 Hits")
        playlist_name = my_playlist.get('name', 'N/A')
        song_count = my_playlist.get('song_count', 0)
        total_duration = my_playlist.get('total_duration', 0)

        if song_count > 0:
            print(f"✓ Playlist: {playlist_name}")
            print(f"  Songs: {song_count}")
            print(f"  Total duration: {total_duration} seconds ({total_duration//60} min {total_duration%60} sec)")
        else:
            print("⚠ Function returns empty playlist - implement Task 2")
            print(f"  Current output: {my_playlist}")
    except Exception as e:
        print(f"✗ Error in Task 2: {e}")

    # Test Task 3
    print("\n--- Task 3: Organize by Artist ---")
    try:
        library = organize_by_artist(test_songs)
        if library:
            print(f"✓ Library has {len(library)} artists")
            for artist, songs in library.items():
                print(f"  {artist}: {len(songs)} song(s)")
        else:
            print("⚠ Function returns empty dictionary - implement Task 3")
    except Exception as e:
        print(f"✗ Error in Task 3: {e}")
        library = {}  # Set to empty dict to avoid errors in later tests

    # Test Task 4
    print("\n--- Task 4: Search and Filter ---")
    try:
        gracie_songs = find_songs_by_artist(library, "Gracie Abrams")
        if gracie_songs:
            print(f"✓ Gracie Abrams songs found: {gracie_songs}")
        else:
            print("⚠ Function returns empty list - implement Task 4a")
            print("  (This is expected if Task 3 is not complete)")
    except Exception as e:
        print(f"✗ Error in Task 4a: {e}")

    try:
        long_songs = find_long_songs(test_songs, 300)
        if long_songs:
            print(f"✓ Songs >= 300 seconds: {len(long_songs)} found")
            for song in long_songs:
                print(f"    {song[0]} by {song[1]} ({song[2]}s / {song[2]//60}:{song[2]%60:02d})")
        else:
            print("⚠ Function returns empty list - implement Task 4b")
    except Exception as e:
        print(f"✗ Error in Task 4b: {e}")

    # Test Task 5
    print("\n--- Task 5: Statistics ---")
    try:
        longest = get_longest_song(test_songs)
        if longest:
            print(f"✓ Longest song: {longest[0]} by {longest[1]}")
            print(f"  Duration: {longest[2]}s ({longest[2]//60}:{longest[2]%60:02d})")
        else:
            print("⚠ Function returns None - implement Task 5a")
    except Exception as e:
        print(f"✗ Error in Task 5a: {e}")

    try:
        top_artist = get_artist_with_most_songs(library)
        if top_artist:
            song_count = len(library.get(top_artist, []))
            print(f"✓ Artist with most songs: {top_artist} ({song_count} songs)")
        else:
            print("⚠ Function returns None - implement Task 5b")
            print("  (This is expected if Task 3 is not complete)")
    except Exception as e:
        print(f"✗ Error in Task 5b: {e}")

    print("\n" + "=" * 60)
    print("Testing complete!")
    print("\n⚠ indicates functions that need implementation")
    print("✓ indicates functions that are working")
    print("✗ indicates functions with errors")
    print("=" * 60)
    #print(create_artist_db(test_artists))
   
    print(build_playlist(test_songs,"Name of PL"))
    #print(find_long_songs(test_songs,250))
    #print(get_longest_song(test_songs))
    #print(organize_by_artist(test_songs))
